package GEMonitor;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AesUtil {

    public static final byte[] key1 = "1111111122222222".getBytes();

    /**
     * 加密
     */
    public static byte[] aesEncode(byte[] content) {
        try {

            SecretKey key = new SecretKeySpec(key1, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");

            //补码到16位
            int plaintextLength = content.length;
            int blockSize = cipher.getBlockSize();


            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(content, 0, plaintext, 0, content.length);

            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(plaintext);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     */
    public static byte[] aesDecode(byte[] content) {
        try {
//
            SecretKey key = new SecretKeySpec(key1, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, key);

            byte[] decode = cipher.doFinal(content);
            int end = decode.length-1;
            while(end>=0 && decode[end]==0x00){
                end--;
            }
            byte[] res = new byte[end+1];
            System.arraycopy(decode,0,res,0,end+1);
            return res;

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException("兄弟，配置文件中的密码需要使用AES加密，请使用AESUtil工具类修改这些值！");
        }
        return null;
    }

    public static void main(String[] args) {


        byte[] aa= new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
        byte[] jimi = aesEncode(aa);
        for(int i=0;i<jimi.length;i++){
            System.out.printf("%02x ",jimi[i]);
        }
        System.out.println("");

        byte[] jiemmi=aesDecode(jimi);

        for(int i=0;i<jiemmi.length;i++){
            System.out.printf("%02x ",jiemmi[i]);
        }

    }

}
